package com.xiaoxin.myhouse;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.xiaoxin.myhouse.mapper.UserMapper;
import com.xiaoxin.myhouse.pojo.Permission;
import com.xiaoxin.myhouse.pojo.Role;
import com.xiaoxin.myhouse.pojo.User;
import com.xiaoxin.myhouse.pojo.UserExample;
import com.xiaoxin.myhouse.pojo.UserExample.Criteria;
import com.xiaoxin.myhouse.service.UserService;

public class AuthRleam extends AuthorizingRealm {
	
	@Autowired
	private UserMapper userMapper;
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next();
		//User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next();
		User us=(User)SecurityUtils.getSubject().getPrincipal();
		User user = userMapper.findByUsername(us.getUsername());
		List<String> permissionList = new ArrayList<>();
		List<String> roleList = new ArrayList<>();
		Set<Role> roles = user.getRoles();
		if(CollectionUtils.isNotEmpty(roles)) {
			for (Role role : roles) {
				roleList.add(role.getRname());
				Set<Permission> permissions = role.getPermissions();
				if(CollectionUtils.isNotEmpty(permissions)) {
					for (Permission permission : permissions) {
						permissionList.add(permission.getName());
					}
				}
			}
			
		}
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(permissionList);
		info.addRoles(roleList);
		return info;
	}
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		String username = userToken.getUsername();
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<User> list = userMapper.selectByExample(example);
		if(list != null && list.size()>0){
			User user = list.get(0);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
			return info;
		}
		return null;
	}


}
